#! /bin/bash

NOWTIME=$(date '+%Y-%m-%d %H:%M:%S')

echo ${NOWTIME}' : begin '

fileName=$1
if [ -z "$fileName" ];then
        echo "参数不能为空"
        exit
fi

NOW=$(date +%Y-%m-%d)
YES=$(date -d -1day +%Y-%m-%d)

# 昨日的文件
oldLineFile=/tmp/${fileName}_line.$YES

# 获取上次检测 末尾行
lineFile=/tmp/${fileName}_line.$NOW

# 监控的日志文件
logFile=/data/logs/${fileName}/${fileName}Exception.log.$NOW
echo 'log_file : '$logFile

# 文件 不存在 退出
if [ ! -f "$logFile" ]; then
        echo '---------------------- end -----------------------'
        exit
fi

# 不存在新建 存在修改 文件使用时间
if [ ! -f "$lineFile" ]; then
        touch "$lineFile"
fi

# 读取 上次统计 到的行数
line=$(cat $lineFile)

if [ ! -n "$line" ]; then
        line=1
fi
echo 'line : '$line


# 统计 新增的行数
riseLine=$(sed -n "${line},$"'p' ${logFile} | wc -l)
newLine=$[ $line+$riseLine ]

echo $riseLine

if [[ $riseLine -eq 0 ]]; then
        echo '---------------------- end -----------------------'
        exit
fi
echo 'newLine: '$newLine

# 写入最新行
echo $newLine > $lineFile

# 统计 内容
content=$(sed -n "${line},${newLine}"'p' ${logFile} | grep 'ERROR' | awk '{M="";for(i=7;i<=NF;i++){M=M$i" ";}print M;}' | sed -e '/"/s/"//g' | awk '{a[$0]++}END{for (j in a) print j,"次数:",a[j]}' | awk '{a[$0]=NR;i=1}END{tx="";for (j in a) {tx=tx"--------------\\n"i". "j"\\n";i++} print tx}')

# 判空
if [ -z "$content" ];then
        echo '---------------------- end -----------------------'
        exit
fi

# content="[${fileName}-ERROR]:"${content}

echo $content

curl https://hook.bearychat.com/=bw84t/incoming/847368f505a2d47a0b315bc92e9282d0 -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"text":"'"$fileName"'-ERROR:","attachments":[{"color":"#ffa500","text":"'"$content"'"}]}'

# curl -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"toUser":"genghaizhou|andy|shiyangtao|duwei","agentId":"15","content":"'"$content"'"}'  http://wx.kuaihaowei.net/sms/send_weixin_msg
# http POST http://wx.kuaihaowei.net/sms/send_weixin_msg @/tmp/${fileName}_content.json

echo ''

# 删除昨日文件
if [ -f "$oldLineFile" ]; then
        rm -f $oldLineFile
fi

echo '---------------------- end -----------------------'

# ( crontab -l 2>/dev/null | grep -Fv "*/10 * * * * /bin/bash /data/bin/wop_error.sh" ; printf -- "*/10 * * * * /bin/bash /data/bin/wop_error.sh >> /tmp/Khw-WOP_NEW-CAUTH_error.log 2>&1"; echo "" ) | crontab

# cat access.log | awk -F'\t' '{$5=504;print $0}' | awk '{split($6, arr, "?");a[arr[1]]++}END{for (j in a) print j,"次数:",a[j]}'
# cat access.log | awk -F'\t' '{if($5=504){split($4, arr, "?");key=arr[1]" "$5;a[key]++;b[key]=b[key]+$10;}}END{for (j in a) print j,"\ttital:",b[j],"\t次数:",a[j]}'
# cat access.log | awk -F'\t' '{if($5=504){split($4, arr, "?");key=arr[1]" "$5;a[key]++;b[key]=b[key]+$10;}}END{for (j in a) print j,"\ttital:",b[j],"\tavg:",b[j]/a[j],"\t次数:",a[j]}' > /tmp/nginx_504.log

